package com.mumu.android.utm;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import  android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.osgeo.proj4j.CRSFactory;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import org.osgeo.proj4j.ProjCoordinate;


public class MainActivity extends AppCompatActivity{
    private TextView tv_direction_value, tv_direction;
    private TextView tv_latitude, tv_latitude_zone, tv_longitude, tv_longitude_zone,
            tv_speed, tv_location_direction ,tv_altitude;
    private TextView tv_latitude2, tv_longitude2;
    private Button btn_location;
    private LinearLayout lv_location_info_error;
    private LocationManager locationManager;
    private String[] directions = {"北", "西北", "西", "西南", "南", "东南", "东", "东北" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        System.out.println("开始");

        initView();
        initCompass();
    }

    private void initView() {
        tv_direction_value = findViewById(R.id.tv_direction_value);
        tv_direction = findViewById(R.id.tv_direction);

        lv_location_info_error = findViewById(R.id.lv_location_info_error);
        btn_location = findViewById(R.id.btn_location);

        tv_latitude = findViewById(R.id.tv_latitude);
        tv_latitude_zone = findViewById(R.id.tv_latitude_zone);
        tv_longitude = findViewById(R.id.tv_longitude);
        tv_longitude_zone = findViewById(R.id.tv_longitude_zone);
        tv_speed = findViewById(R.id.tv_speed);
        tv_location_direction = findViewById(R.id.tv_location_direction);
        tv_altitude = findViewById(R.id.tv_altitude);

        tv_altitude.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        tv_latitude2 = findViewById(R.id.tv_latitude2);
        tv_longitude2 = findViewById(R.id.tv_longitude2);

    }


    private void initCompass(){
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

        SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float azimuth = event.values[0];
                updateCompass(azimuth);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);
    }

    private void updateCompass(float azimuth){

        tv_direction.setText(getDirection(-azimuth));

        tv_direction_value.setText((int)azimuth+"°");
        if ((int)azimuth==0 | (int)azimuth==359){
            tv_direction_value.setText("0°");
            tv_direction.setText("正北");
            tv_direction.setTextColor(Color.RED);
            tv_direction_value.setTextColor(Color.RED);
        } else {
            tv_direction.setTextColor(Color.WHITE);
            tv_direction_value.setTextColor(Color.WHITE);
        }
    }

    private String getDirection(float azimuth) {
        azimuth = (azimuth + 360) % 360;
        int index = Math.round(azimuth / 45f) % 8;
        return directions[index];
    }

    private void locationInit(){
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!isLocationEnabled(locationManager)){
            showError();
            showLocationEnableDialog(1);
        }

        if (!checkLocationPermission()){
            showError();
            showLocationEnableDialog(2);
        }
    }

    private boolean isLocationEnabled(LocationManager locationManager) {
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gpsEnabled || networkEnabled;
    }

    private void requestLocationSettings() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 200);
    }

    private boolean checkLocationPermission() {
        boolean fineLocationPermissionGranted = ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean coarseLocationPermissionGranted = ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

        return fineLocationPermissionGranted && coarseLocationPermissionGranted;
    }

    private void requestLocationPermission() {
        ActivityCompat.requestPermissions(this,
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION },
                200);

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // 第一次请求权限，或用户点击了"拒绝"但没有勾选"不再询问"选项
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    200);
        } else {
            // 用户点击了"拒绝"并勾选了"不再询问"选项或之前已经请求过权限并被用户拒绝（没有勾选"不再询问"选项）
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts("package", getPackageName(), null));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }


    private void showLocationEnableDialog(int code) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("重要提示");
        if (code==1) builder.setMessage("\n软件需要使用定位功能来提供服务，设备定位功能已关闭，是否前往开启？\n");
        if (code==2) builder.setMessage("\n为正常使用软件功能，请设置相关权限！\n");

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // 跳转到系统设置界面开启定位
                        if (code==1){
                            requestLocationSettings();
                        }
                        if (code==2){
                            requestLocationPermission();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // 用户点击取消，处理相关逻辑
                        dialog.dismiss();
                    }
                });

        // 创建对话框并显示
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private void showError(){
        lv_location_info_error.setVisibility(View.VISIBLE);
        btn_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                locationInit();
            }
        });
    }

    private void hindError(){
        lv_location_info_error.setVisibility(View.GONE);
    }


    private BroadcastReceiver updateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.abdusalam.Location_Data")) {
                System.out.println("广播接收数据");
                double latitude = intent.getDoubleExtra("latitude", 0.0);
                double longitude = intent.getDoubleExtra("longitude", 0.0);
                float speed = intent.getFloatExtra("speed", 0.0f);
                float bearing = intent.getFloatExtra("bearing", 0.0f);
                double altitude = intent.getDoubleExtra("altitude", 4.0);
                locationUpdate(latitude, longitude, speed, bearing, altitude);
            }
        }
    };


    private void locationUpdate(double latitude, double longitude, double speed,
                                double direction, double altitude){
        tv_latitude_zone.setText(latitude >= 0 ? "北纬" : "南纬");
        tv_latitude.setText(latitude+"");
        tv_longitude_zone.setText(longitude >= 0 ? "东经" : "西经");
        tv_longitude.setText(longitude+"");

        tv_speed.setText(String.format("%.2f(m/s)", speed));

        tv_location_direction.setText(String.format("%.1f°", direction));
        tv_altitude.setText(String.format("%.2f(m)", altitude));


        // 定义WGS84坐标系
        CRSFactory crsFactory = new CRSFactory();
        CoordinateReferenceSystem wgs84 = crsFactory.createFromName("EPSG:4326");

        // 定义UTM坐标系
        CoordinateReferenceSystem utm = crsFactory.createFromName("EPSG:32650"); // 示例使用UTM50N
        // 转换为UTM坐标
        ProjCoordinate sourceCoord = new ProjCoordinate(latitude, longitude);
        ProjCoordinate targetCoord = new ProjCoordinate();

        utm.getProjection().projectRadians(sourceCoord,targetCoord);

        System.out.println("UTM东北坐标 X: " + targetCoord.x + ", Y: " + targetCoord.y);
        tv_latitude2.setText((targetCoord.x)+"");
        tv_longitude2.setText((targetCoord.y)+"");







    }



    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter("com.abdusalam.Location_Data");
        registerReceiver(updateReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationInit();
        Intent serviceIntent = new Intent(this, AbduLocationService.class);
        startService(serviceIntent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(updateReceiver);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 200) {
            boolean isLocationEnabled = isLocationEnabled(locationManager);
            if (isLocationEnabled) {
                if (checkLocationPermission()){
                    hindError();
                }
            } else {
                btn_location.setText("开启定位");
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 200) {
            // 检查权限授予结果
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (isLocationEnabled(locationManager)){
                    hindError();
                } else {
                    btn_location.setText("设置权限");
                }
            }
        }
    }


}